from uuid import UUID
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select, delete
from sqlalchemy.exc import IntegrityError

from models.relation import RiskGuaranteeRelation
from schemas.relation import RiskGuaranteeRelationCreate
from log import log_error, log_info

async def create_relation(
    db: AsyncSession, 
    relation: RiskGuaranteeRelationCreate
) -> RiskGuaranteeRelation:
    """创建风险与保障关联"""
    try:
        db_relation = RiskGuaranteeRelation(**relation.model_dump())
        db.add(db_relation)
        await db.commit()
        await db.refresh(db_relation)
        log_info(f"Created relation between risk {relation.risk_item_id} and guarantee {relation.guarantee_item_id}")
        return db_relation
    except IntegrityError as e:
        log_error(f"Failed to create relation: {str(e)}")
        await db.rollback()
        raise

async def get_relation(
    db: AsyncSession, 
    relation_id: UUID
) -> RiskGuaranteeRelation | None:
    """获取指定ID的关联关系"""
    query = select(RiskGuaranteeRelation).where(RiskGuaranteeRelation.id == relation_id)
    result = await db.execute(query)
    return result.scalar_one_or_none()

async def get_relations_by_risk(
    db: AsyncSession, 
    risk_item_id: UUID
) -> list[RiskGuaranteeRelation]:
    """获取指定风险项的所有关联关系"""
    query = select(RiskGuaranteeRelation).where(RiskGuaranteeRelation.risk_item_id == risk_item_id)
    result = await db.execute(query)
    return list(result.scalars().all())

async def update_relation(
    db: AsyncSession,
    relation_id: UUID,
    relation_update: RiskGuaranteeRelationCreate
) -> RiskGuaranteeRelation | None:
    """更新指定ID的关联关系"""
    try:
        result = await db.execute(
            select(RiskGuaranteeRelation)
            .where(RiskGuaranteeRelation.id == relation_id)
        )
        db_relation = result.scalar_one_or_none()
        if db_relation is None:
            return None
            
        for key, value in relation_update.model_dump().items():
            setattr(db_relation, key, value)
            
        await db.commit()
        await db.refresh(db_relation)
        log_info(f"Updated relation {relation_id}")
        return db_relation
    except IntegrityError as e:
        log_error(f"Failed to update relation {relation_id}: {str(e)}")
        await db.rollback()
        raise

async def delete_relation(
    db: AsyncSession, 
    relation_id: UUID
) -> bool:
    """删除指定ID的关联关系"""
    query = delete(RiskGuaranteeRelation).where(RiskGuaranteeRelation.id == relation_id)
    result = await db.execute(query)
    await db.commit()
    deleted = result.rowcount > 0
    if deleted:
        log_info(f"Deleted relation {relation_id}")
    return deleted 